import request from '@/utils/request'

// 获取成就列表
export function getProjects(params) {
  return request({
    url: '/api/projects',
    method: 'get',
    params 
  })
}

// 根据ID获取项目详情
export function getProjectDetail(id) {
  return request({
    url: `/api/projects/${id}`,
    method: 'get'
  })
}

// 根据项目ID获取所有提交记录
export function getSubmissions(id) {
  return request({
    url: `/api/projects/${id}/assignment/submissions`,
    method: 'get'
  })
}

export function createProjects(data) {
  // Create a FormData object for file uploads
  const formData = new FormData()
  
  // Map frontend field names to backend field names
  const fieldMapping = {
    'description': 'comment',
    'endTime': 'finishTime',
    'documentFile': 'file'
  }
  
  // Add all data fields to the FormData
  Object.keys(data).forEach(key => {
    if (key === 'startTime' || key === 'endTime') {
      // Format date objects to strings
      if (data[key]) {
        const backendKey = fieldMapping[key] || key
        formData.append(backendKey, data[key].format('YYYY-MM-DD HH:mm:ss'))
      }
    } else if (key !== 'document' && key !== 'documentFile') {
      // Add all other fields except document and documentFile
      const backendKey = fieldMapping[key] || key
      formData.append(backendKey, data[key])
    }
  })
  
  // Add the document file if it exists
  if (data.documentFile) {
    formData.append('file', data.documentFile)
  }
  
  return request({
    url: '/api/projects',
    method: 'POST',
    data: formData,
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  })
}

// 删除项目
export function deleteProject(id) {
  return request({
    url: `/api/projects/${id}`,
    method: 'delete'
  })
}